package org.etlt.load;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.etlt.job.JobContext;
import org.etlt.job.JobSetting;
import org.etlt.job.SettingResolver;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class LoaderFactory {

    protected Log log = LogFactory.getLog(getClass());
    private static final LoaderFactory LOADER_FACTORY = new LoaderFactory();

    private LoaderFactory(){}

    public static LoaderFactory getInstance(){
        return LOADER_FACTORY;
    }

    private SettingResolver<LoaderSetting> settingResolver;

    protected void populateSettingResolver(String resourceName) {
        if(JobSetting.isXml(resourceName))
            this.settingResolver = new LoaderSettingXmlResolver();
        else throw new IllegalStateException("unsupported extract file: " + resourceName);
    }


    public List<Loader> resolveInstance(String settingFile,final JobContext context) throws IOException {
        populateSettingResolver(settingFile);
        List<Loader> results = new ArrayList<>();
        File file = new File(context.getContextRoot(), settingFile);
        log.info("start: resolve loader(s) from file: " + file);
        InputStream stream = new FileInputStream(file);
        List<LoaderSetting> loaderSettings =
                settingResolver.resolveBundle(stream, context);
        if(!loaderSettings.isEmpty()){
            loaderSettings.forEach((setting)->{
                results.add(createLoader(setting, context));
            });
        }
        else {
            stream = new FileInputStream(new File(context.getContextRoot(), settingFile));
            results.add(createLoader(settingResolver.resolve(stream, context), context));
        }
        log.info("end: resolve loader(s) from file: " + file);
        return results;
    }



    public Loader createLoader(LoaderSetting setting, JobContext context) {
        if (setting instanceof FileLoaderSetting) {
            return new FileLoader((FileLoaderSetting) setting);
        } else if (setting instanceof DatabaseLoaderSetting) {
            return new DatabaseLoader((DatabaseLoaderSetting) setting);
        }
        throw new IllegalArgumentException("unsupported loader setting: " + setting.getName());
    }
}
